package actions;

import java.sql.SQLException;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.RowSet;

import model.StudentModel;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import db.DbException;
import forms.SpecializationForm;
//import forms.StudentForm;
import model.AdminModel;

public class AdminGetSpecializationResultsAction extends Action {

	private static final boolean DEBUG = true;

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws DbException {
		
		// get discipline from form
		SpecializationForm sform = (SpecializationForm)form;
		String specialization = sform.getSpecialization();
		
		Vector<String> names = new Vector<String>();
		Vector<String> gpas = new Vector<String> ();
		Vector<String> statuses = new Vector<String>();
		Vector<String> app_id = new Vector<String>();
		
		String path = mapping.getPath();
		
		if (DEBUG) {
			System.err.println("AdminGetSpecializationResultsAction: " + path);
		}
		// Get the result from the query
		try {
			RowSet applications = AdminModel.getApplicationsBySpecialization(specialization);
			while(applications.next())
			{
				// 1. Retrieve all names with given specialization
				String fullname = applications.getString("first_name") + " "
								+ applications.getString("middle_name") + " "
								+ applications.getString("last_name");
				names.add(fullname);
				
				// 2. Calculate average gpa
				RowSet degrees = AdminModel.getDegreesBySpecialization(applications.getInt("id"));
				int num = 0;
				float total = 0;
				
				while(degrees.next())
				{
					num++;
					total += degrees.getFloat("gpa");
				}
				float average = total / num;
				gpas.add(Float.toString(average));
				
				// 3. Retrieve admission status
				statuses.add(applications.getString("admission_status"));
				
				// 4. Add student ID for input into status change
				app_id.add(Integer.toString(applications.getInt("id")));
				
			}
		
		} catch (SQLException ex) {
			throw new DbException(ex);
		}
		
		// Store the Vectors in the request scope
		request.getSession().setAttribute("names", names);
		request.getSession().setAttribute("gpas", gpas);
		request.getSession().setAttribute("statuses", statuses);
		request.getSession().setAttribute("app_id", app_id);
		
		//Store a value into request to know which to load after status change
		request.setAttribute("input", "specializations");

		
		return mapping.findForward("success");
	}
}